﻿using UnityEngine;

namespace GameCore
{
    public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
    {
        /// <summary>
        ///   单例实例
        /// </summary>
        private static T m_instance = null;
        public static T Instance
        {
            get
            {
                if (m_instance == null)
                {
                    m_instance = UnityEngine.Object.FindObjectOfType(typeof(T)) as T;
                    if (m_instance == null)
                    {
                        if (Application.isPlaying)
                        {
                            m_instance = new GameObject(typeof(T).Name).GetAndAddComponent<T>();
                            DontDestroyOnLoad(m_instance);
                        }
                    }
                }
                return m_instance;
            }
        }
     
        /// <summary>
        ///  创建单例实例
        /// </summary>
        public static T CreateSingleton()
        {
            return Instance;
        }

        /// <summary>
        ///   确保在程序退出时销毁实例。
        /// </summary>
        protected virtual void OnApplicationQuit()
        {
            m_instance = null;
        }
    }
 
}
